import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.libvirt.Connect;
import org.libvirt.ConnectAuth;
import org.libvirt.ConnectAuthDefault;
import org.libvirt.Domain;
import org.libvirt.DomainInfo;
import org.libvirt.LibvirtException;
import org.libvirt.Network;

public class TestConnection {

	private static final String DASH = "------------------------------------------";
	// Use this to flag errors in the test run.
	public static String FIXME = "<============== FIXME ================> ";

	public static void main(String[] args) {
		// Create the connection
		Connect conn = null;
		Domain d = null;
		String out = "";
		Network testNetwork = null;
		ConnectAuth defaultAuth = new ConnectAuthDefault();
		boolean flag = true;

		try {
			if (args == null || (args.length < 3)) {
				System.out
						.println("\n\"run TestConnection ip [localhost|root@192.168.149.39] list\" to list all domains.");
				System.out
						.println("\n\"run TestConnection ip [localhost|root@192.168.149.39] destroy id_to_destroy xml_domain\" to destroy a domain.");
				System.out
						.println("\"run TestConnection ip [localhost|root@192.168.149.39] create xml_file_domain\" to create a domain.");
				System.out
						.println("\"run TestConnection ip [localhost|root@192.168.149.39] migrate id_to_migrate uri\" to migrate a domain.");
				System.out
						.println("To create a XML file from a cfg image use = \"virsh -c xen:/// domxml-from-native xen-xm /etc/xen/imagem-004.cfg\"");
				flag = false;
			}

			if (flag && args[0].equals("ip") && args[1].equals("localhost")) {
				conn = new Connect("xen:///", defaultAuth, 0);
				System.out.println("Encrypted connection successful!");

			} else if (flag && args[0].equals("ip")
					&& !args[0].equals("localhost")) {
				String uri = args[1];
				conn = new Connect("xen+ssh://" + uri + "/", false);
				System.out.println("Encrypted connection successful!");
			} else {
				flag = false;
			}

			if (flag) {
				if (args[2].equals("list")) {
					System.out.println("Capabilities: "
							+ conn.getCapabilities());
					System.out.println("hostname: " + conn.getHostName());
					System.out.println("version: " + conn.getLibVirVersion());
					System.out.println("isSecure: " + conn.isSecure());
					System.out.println("isEncrypted: " + conn.isEncrypted());
					System.out.println("numOfDomains: " + conn.numOfDomains());
					System.out.println("active Domains: "
							+ conn.listDomains().length);

					int[] ids = conn.listDomains();
					System.out.println("Domains informations");
					for (int i : ids) {
						d = conn.domainLookupByID(i);
						getDomainInfo(d);
					}
					System.out.println(DASH);
				} else if (args[2].equals("destroy")) {
					try {
						int idToDelete = Integer.parseInt(args[3]);
						d = conn.domainLookupByID(idToDelete);
						if (d != null) {
							System.out.println("Destruindo um Domain...");
							d.destroy();
						} else {
							System.out.println("Domain não encontrado.");
						}
					} catch (NumberFormatException e) {
						System.out.println("The ID is not a number");
					}
				} else if (args[2].equals("create")) {
					try {
						File f = new File(args[3]);
						if (!f.exists()) {
							System.out.println("File xml does not exist!");
							throw new IOException();
						}
						BufferedReader in = new BufferedReader(
								new FileReader(f));
						String str = "";
						while ((str = in.readLine()) != null) {
							out = out + str;
						}
						in.close();

						// Define a new Domain
						System.out.println("Criando um Domain...");
						// System.out.println("conn.domainDefineXML:"+
						// conn.domainDefineXML(out));

						System.out.println("conn.domainCreateLinux:"
								+ conn.domainCreateLinux(out, 0));
						System.out.println("Domain criado...");
					} catch (IOException e) {
					}
				} else if (args[2].equals("migrate")) {
					try {
						int idToMigrate = Integer.parseInt(args[3]);
						String dcon = args[4];
						Connect dconn = new Connect(dcon, defaultAuth, 0);
						d = conn.domainLookupByID(idToMigrate);
						if (d != null) {
							System.out.println("Migrando um Domain...");
							d.migrate(dconn, 1, null, null, 0);
						} else {
							System.out.println("Domain não encontrado.");
						}
					} catch (NumberFormatException e) {
						System.out.println("The ID is not a number");
					}
				}
			}
		} catch (LibvirtException e) {
			System.out.println(FIXME);
			System.out.println("exception caught:" + e);
			System.out.println(e.getError());
		}

		System.out.println("Done!");
	}

	private static void getDomainInfo(Domain d) throws LibvirtException {
		System.out.println(DASH);
		System.out.println("Domain name = " + d.getName() + " | ID = "
				+ d.getID() + " | OSType = " + d.getOSType());
		System.out.println("MaxMemory = " + d.getMaxMemory() + " | "
				+ d.getMaxVcpus());
		System.out.println("UUID = " + d.getUUIDString());
		System.out.println("Active? = " + d.isActive());
		System.out.println("Persistent? = " + d.isPersistent());

		DomainInfo df = d.getInfo();
		System.out.println("CPUTime = " + df.cpuTime);
		System.out.println("MaxMem = " + df.maxMem);
		System.out.println("memory = " + df.memory);
		System.out.println("nrVirtCpu = " + df.nrVirtCpu);
		System.out.println("state = " + df.state);

	}
}
